package com.lzx.payment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.common.utils.R;
import com.lzx.payment.entity.OrderInfo;
import com.lzx.payment.entity.RefundInfo;
import com.lzx.payment.mapper.RefundInfoMapper;
import com.lzx.payment.service.OrderInfoService;
import com.lzx.payment.service.RefundInfoService;
import com.lzx.payment.util.OrderNoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-12-19
 */
@Service
public class RefundInfoServiceImpl extends ServiceImpl<RefundInfoMapper, RefundInfo> implements RefundInfoService {
    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private RefundInfoMapper refundInfoMapper;

    //根据订单号创建退款订单
    @Override
    public RefundInfo createRefundByOrderNoForAliPay(String orderNo, String reason) {
        //根据订单号获取订单信息
        OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
        //根据订单号生成退款订单
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setOrderNo(orderNo);//订单编号
        refundInfo.setRefundNo(OrderNoUtils.getRefundNo());//退款单编号
        refundInfo.setTotalFee(orderInfo.getTotalFee());//原订单金额(分)
        refundInfo.setRefund(orderInfo.getTotalFee());//退款金额(分)
        refundInfo.setReason(reason);//退款原因
        //保存退款订单
        refundInfoMapper.insert(refundInfo);
        return refundInfo;
    }

    //更新退款记录
    @Override
    public void updateRefundForAliPay(String refundNo, String content, String refundStatus) {
        //根据退款单编号修改退款单
        QueryWrapper<RefundInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("refund_no", refundNo);
        //设置要修改的字段
        RefundInfo refundInfo = new RefundInfo();
        refundInfo.setRefundStatus(refundStatus);//退款状态
        refundInfo.setContentReturn(content);//将全部响应结果存入数据库的content字段
        //更新退款单
        refundInfoMapper.update(refundInfo, queryWrapper);
    }

    //获取退款列表
    @Override
    public R getRefundInfoList(int current, int size) {
        Page<RefundInfo> page = new Page<>(current, size);
        refundInfoMapper.selectPage(page, null);
        Map<String, Object> map = new HashMap<>();
        List<RefundInfo> list = page.getRecords();//当前页数据
        long total = page.getTotal();//总记录数
        map.put("list", list);
        map.put("total", total);
        return R.ok().data("map", map);
    }
}
